<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../vue.js"></script>
  </head>

  <body>
    <div id="app">
      <input type="text" v-model="search" />
      <button @click="type=2">升序</button>
      <button @click="type=1">降序</button>
      <button @click="type=0">默认</button>
      <ul>
        <li v-for="item in finallyPersons" :key="item.id">
          姓名:{{item.name}}---年龄:{{item.age}}
        </li>
      </ul>
    </div>
    <script>
      Vue.config.productionTip = false;

      const vm = new Vue({
        el: "#app",
        data() {
          return {
            search: "",
            /* 
              在排序搜索过滤等等操作中,我们尽量不要操作原来的数据,因为我们可能还要回去最初的操作
              一般来说过滤等操作都是重新定义一个数据保存过滤后的值
            */
            persons: [
              { id: "001", name: "周杰伦", age: 19 },
              { id: "002", name: "陈奕迅", age: 25 },
              { id: "003", name: "周杰", age: 39 },
              { id: "004", name: "陈冠希", age: 7 },
              { id: "005", name: "谢坤", age: 22 },
              { id: "006", name: "杨坤", age: 14 },
              { id: "007", name: "谢霆锋", age: 11 },
            ],
            type: 0,
          };
        },
        computed: {
          finallyPersons() {
            const filterPersons = this.persons.filter((item) => {
              return item.name.includes(this.search);
            });

            /* if (this.type === 0) {
              return filterPersons;
            } else if (this.type === 1) {
              return filterPersons.sort((a, b) => {
                return b.age - a.age;
              });
            } else {
              return filterPersons.sort((a, b) => {
                return a.age - b.age;
              });
            } */
            switch (this.type) {
              case 1:
                return filterPersons.sort((a, b) => {
                  return b.age - a.age;
                });
              case 2:
                return filterPersons.sort((a, b) => {
                  return a.age - b.age;
                });
              default:
                return filterPersons;
            }
          },
        },
      });
    </script>
  </body>
</html>
